//项目权属管理
import * as React from 'react';
import {
  Table,
  Form,
  Select,
  Input,
  Button,
  Col,
  Row,
  Modal,
  Tree,
  Card,
  Icon,
  Popover,
  Checkbox ,
  notification
} from 'antd';
import axios from 'axios'
import Api from '../../services/apis'

import Link from 'umi/link';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { func } from 'prop-types';

const FormItem = Form.Item;
const Option = Select.Option;
const TreeNode = Tree.TreeNode;
const { Meta } = Card;
const CheckboxGroup = Checkbox.Group;

@connect(({ user, project, activities, chart, loading }) => ({
  currentUser: user.currentUser,
  currentUserLoading: loading.effects['user/fetchCurrent']
}))

class KeyManagement extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      tableData: [],
      m_tableData: [],
      current: 1,
      pageSize: 5,
      m_current: 1,
      m_pageSize: 5,
      submitFlag : '',
      rooms:[],
      cabinets:[],
      boxs:[],
      bags:[],
      keyId: '',
    };
  }

  sendData = () => {
    const that = this;
    const searchValues = this.props.form.getFieldsValue();
    axios.post(Api.kmGetKeyList,{
      keyName: searchValues.s_name,
      keyStatus: searchValues.s_state,
      currentPage: this.state.current
    })
    .then((function(resp){
        const data = resp.data;
        if(data.list.length === 0){
            notification.destroy();
            notification['warning']({message:'暂无数据'})
        }else{
            data.list.forEach((d,i) => {
                d.key = i;
                d.key_status = d.key_status === '0' ? "未借出" : parseInt(d.key_status) < 4 ? '审批中' : "已借出";
            });
        }

        that.setState({
            tableData: data.list,
            pageSize: data.pageSize,
            current: data.currentPage,
            totalSize: data.totalSize
        })
    }))
  }

  componentWillMount(){
        
      //请求数据
      this.sendData();

      //获取房间下拉
      this.getRoomList();

      //获取卡种类
      this.getKeySpecies();
  }

  //获取房间下拉
  getRoomList = () => {
    const that = this;
    axios.post(Api.rmGetPositionList,{})
    .then(function(resp){
        that.setState({
            rooms: resp.data
        })
    })
  }

  //获取卡种类
  getKeySpecies = () => {
    const that = this;
    axios.post(Api.kmGetKeySpecies,{})
    .then(function(resp){
      const {data} = resp;
      data.forEach(item => {
        item.label = item.dicName;
        item.value = item.dicCode;
      })
      that.setState({
        keySpecies: data
      })
    })
  }
  
  //根据房间获取柜子/根据柜子过去档案盒
  getPositionList = (type,value) => {
      const that = this;
      return axios.post(Api.rmGetPositionListByParentList,{
          parentId : value
      })
      .then(function(resp){
          if(type=="cabinets"){
              that.setState({
                  cabinets: resp.data
              })
              that.props.form.setFieldsValue({
                m_cabinet: '',
                m_box: '',
                m_bag: ''
              })
          }else{
              that.setState({
                  boxs: resp.data
              })
              that.props.form.setFieldsValue({
                m_box: '',
                m_bag: ''
              })
          }
      })
  }
  
  //根据档案盒获取档案袋
  getPackageList = (value) => {
    const that = this;
    return axios.post(Api.rmGetPackageList,{
        positionId : value
    })
    .then(function(resp){
      that.setState({
          bags: resp.data
      })
      that.props.form.setFieldsValue({
        m_bag: ''
      })
    })
  }

  //获取借款记录
  getRecord = (id) => {
      const that = this;
      axios.post(Api.kmGetRecordList,{
        keyId: id,
        currentPage: that.state.m_current
      })
      .then(function(resp){
          const { data } = resp;
          if(data.list && data.list.length !== 0){
              data.list.forEach((d,i) => {
                  d.key = i;
              });
          }

          that.setState({
              m_tableData: data.list,
              m_pageSize: data.pageSize,
              m_current: data.currentPage,
              m_totalSize: data.totalSize
          })
      })
  }

  setModalVisible(modalVisible) {
    this.setState({ modalVisible });
  }

  //新建、修改开启模态框
  openModal = (type,id) => {
    const that = this;
    this.setState({submitFlag:type}); 
    if(type != 'add'){
        //根据ID查询信息
        axios.post(Api.kmGetKeyById,{
          keyId:id
        })
        .then(function(resp){
            const data = resp.data;
            that.setModalVisible(true);
            const state = data.key_status == '0' ? '0' : '1';
            that.props.form.setFieldsValue({
                m_number: data.key_code,
                m_name: data.key_name,
                m_num: data.key_num,
                m_room: data.housedesc,
                m_cabinet: data.cabinetdesc,
                m_box: data.boxdesc,
                m_bag: data.package_name,
                m_state: state,
                m_keySpecie: data.key_species.split(',')
            })
            that.setState({keyId:id, key_status:data.key_status});

            //根据房间获取柜下拉
            that.getPositionList('cabinets',data.houseid)
            .then(function(){
                that.props.form.setFieldsValue({m_cabinet:data.cabinetid})
                
                //根据柜获取盒下拉
                that.getPositionList('boxs',data.cabinetid)
                .then(function(){
                    that.props.form.setFieldsValue({m_box:data.boxid})

                    //根据盒获取袋
                    that.getPackageList(data.boxid)
                    .then(function(){
                      that.props.form.setFieldsValue({m_bag:data.package_id})
                    })
                })
            })


            that.getRecord(id);
        })
    }else{
      that.setModalVisible(true);
      this.props.form.setFieldsValue({
          m_number: "",
          m_name: "",
          m_cabinet: "",
          m_room: "",
          m_box: "",
          m_state: "0",
          m_bag:'',
          m_num:'',
          m_keySpecie:[]
      })
    }
  }

  //新建/修改
  modalSubmit = ()=> {
      const that = this;
      if(that.state.submitFlag == 'show'){
        that.setModalVisible(false);
        return;
      }
      that.props.form.validateFields((err,values)=>{
          if(!err){
              let url = ''
              let param = {
                packageId: values.m_bag,
                keyName: values.m_name,
                keyStatus: values.m_state,
                keyCode: values.m_number,
                keyNum: parseInt(values.m_num),
                keySpecies: values.m_keySpecie.join(',')
              }
              if(this.state.submitFlag == "add"){//新增
                  url = Api.kmAddKey;
              }else if(this.state.submitFlag == "edit"){//更新
                  url = Api.kmUpdateKey;
                  param.keyId = that.state.keyId;
                  param.keyStatus = param.keyStatus == '0' ? '0' : (that.state.key_status == '0' ? '1' : that.state.key_status);
              }
              axios.post(url,param)
              .then(function(resp){
                  const data = resp.data;
                  if(data.flag === '0'){
                      notification.destroy();
                      notification['warning']({message:data.msg});
                  }else if(data.flag === '1'){
                      notification.destroy();
                      notification['success']({message:data.msg});
                      that.sendData();
                  }
                  that.setModalVisible(false);
              })
          }
      })
  }

  resetForm = () => {
    this.props.form.resetFields();
  }

  query = (e) => {
      e.preventDefault();
      this.setState({current:1},()=>{
          this.sendData();
      })
  }

  pageChange = (page) => {
      this.setState({current:page},()=>{
          this.sendData();
      })
  }

  render() {
    const that = this;
    const { getFieldDecorator } = this.props.form;
    const {
      currentUserLoading,
    } = this.props;

    const columns = [
      {
        title: '钥匙名称',
        dataIndex: 'key_name',
        key: 'key_name',
      },
      {
        title: '钥匙位置',
        dataIndex: 'cabinetdesc',
        key: 'cabinetdesc',
      },
      {
        title: '抽屉所在房间',
        dataIndex: 'housedesc',
        key: 'housedesc'
      },
      {
        title: '钥匙状态',
        dataIndex: 'key_status',
        key: 'key_status',
      },
      {
        title: '钥匙数量',
        dataIndex: 'key_num',
        key: 'key_num',
      },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
            <a href="javascript:;" onClick={()=>this.openModal("show",record.key_id)}>
                详情
            </a>
            &emsp;
            <a href="javascript:;" onClick={()=>this.openModal("edit",record.key_id)}>
                编辑
            </a>
          </span>
        ),
      },
    ];

    
    const m_columns = [
      {
          title: '借取人',
          key: 'borrowuser',
          dataIndex: 'borrowuser',
      },
      {
          title: '借取日期',
          key: 'borrowstart',
          dataIndex: 'borrowstart',
      },
      {
          title: '借取事由',
          key: 'borrowcause',
          dataIndex: 'borrowcause',
      },
      {
          title: '归还日期',
          key: 'returndate',
          dataIndex: 'returndate',
      },
      {
          title: '审批人',
          key: 'auditdeptname',
          dataIndex: 'auditdeptname',
      },
      {
          title: '经办人',
          key: 'chargedeptname',
          dataIndex: 'chargedeptname',
      },
      {
          title: '经办部门领导',
          key: 'chargepersonname',
          dataIndex: 'chargepersonname',
      }
  ]

    return (
      <PageHeaderWrapper
        loading={currentUserLoading}
      >
        <div className='mainContainer'>
          <div className='contentHeader'>
            <div className="contentHeaderTitle">
              <p>钥匙管理</p>
              <p>KEY MANAGEMENT</p>
            </div>
          </div>
          <div className="pom">
            <div className='mrb15'>
                <Form layout='inline' align='center' onSubmit={this.query}>
                    <FormItem label="钥匙名称：">
                        {
                            getFieldDecorator('s_name')(
                                <Input placeholder="请输入钥匙名称"/>
                            )
                        }
                    </FormItem>
                    <FormItem label='钥匙状态：'>
                        {
                            getFieldDecorator('s_state')(
                                <Select placeholder="请选择钥匙状态">
                                    <Option value="0">未借出</Option>
                                    <Option value="1">已借出</Option>
                                </Select>
                            )
                        }
                    </FormItem>
                    <Row gutter={24} style={{ textAlign: 'center'}}>
                        <Button icon='search' type='primary' htmlType='submit'>搜索</Button>&emsp;
                        <Button icon="plus-circle" type="primary" htmlType='button' onClick={()=>this.openModal("add")}>新建</Button>&emsp;
                        <Button icon="reload" type="primary" htmlType='button' onClick={this.resetForm}>重置</Button>
                    </Row>
                </Form>
            </div>
            <Table
              bordered={true}
              scroll={{ x: true }}
              columns={columns}
              dataSource={that.state.tableData}
              pagination={{
                defaultPageSize: that.state.pageSize,
                current: that.state.current,
                onChange: that.pageChange,
                total: that.state.totalSize,
                showTotal: total => `共 ${total} 项`
              }}/>
          </div>
          <Modal
            title='钥匙详情'
            centered
            visible={this.state.modalVisible}
            onOk={this.modalSubmit}
            onCancel={()=>this.setModalVisible(false)}
            width={830}
            className='oaomodal'
          >
            <Row gutter={24}>
                <Col span={8}>
                    <FormItem label='钥匙编号：'>
                        {getFieldDecorator('m_number',{
                            rules:[{required:true,message:'请输入钥匙编号！'}]
                        })(<Input placeholder="请输入钥匙编号" disabled={this.state.submitFlag == 'show' ? true : false}/>)}
                    </FormItem>
                </Col>
                <Col span={8}>
                    <FormItem label='钥匙名称：'>
                        {getFieldDecorator('m_name',{
                            rules:[{required:true,message:'请输入钥匙名称！'}]
                        })(<Input placeholder="请输入钥匙名称" disabled={this.state.submitFlag == 'show' ? true : false}/>)}
                    </FormItem>
                </Col>
                <Col span={8}>
                    <FormItem label='所在房间：'>
                        {getFieldDecorator('m_room',{
                            rules:[{required:true,message:'请选择所在房间！'}]
                        })(<Select style={{width:"100%"}} placeholder="请选择所在房间" onChange={(value)=>this.getPositionList("cabinets",value)} disabled={this.state.submitFlag == 'show' ? true : false}>
                            {this.state.rooms.map((item,index)=>
                                <Option key={index} value={item.positionId}>{item.positionDesc}</Option>
                            )}
                        </Select>)}
                    </FormItem>
                </Col>
                <Col span={8}>
                    <FormItem label='所在柜：'>
                        {getFieldDecorator('m_cabinet',{
                            rules:[{required:true,message:'请选择所在柜！'}]
                        })(<Select style={{width:"100%"}}placeholder="请选择所在柜" onChange={(value)=>this.getPositionList('boxs',value)} disabled={this.state.submitFlag == 'show' ? true : false}>
                            {this.state.cabinets.map((item,index)=>
                                <Option key={index} value={item.positionId}>{item.positionDesc}</Option>
                            )}
                        </Select>)}
                    </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label='所在抽屉：'>
                      {getFieldDecorator('m_box',{
                          rules:[{required:true,message:'请选择所在抽屉！'}]
                      })(<Select style={{width:"100%"}}placeholder="请选择所在抽屉" onChange={(value)=>this.getPackageList(value)} disabled={this.state.submitFlag == 'show' ? true : false}>
                          {this.state.boxs.map((item,index)=>
                              <Option key={index} value={item.positionId}>{item.positionDesc}</Option>
                          )}
                      </Select>)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label='所在袋：'>
                      {getFieldDecorator('m_bag',{
                          rules:[{required:true,message:'请选择所在袋！'}]
                      })(<Select style={{width:"100%"}}placeholder="请选择所在袋" disabled={this.state.submitFlag == 'show' ? true : false}>
                          {this.state.bags.map((item,index)=>
                              <Option key={index} value={item.packageId}>{item.packageName}</Option>
                          )}
                      </Select>)}
                  </FormItem>
                </Col>
                <Col span={8}>
                    <FormItem label='钥匙数量：'>
                        {getFieldDecorator('m_num',{
                            rules:[{required:true,message:'请输入钥匙数量！'}]
                        })(<Input placeholder="请输入钥匙数量" disabled={this.state.submitFlag == 'show' ? true : false}/>)}
                    </FormItem>
                </Col>
                <Col span={8}>
                    <FormItem label='钥匙状态：'>
                        {getFieldDecorator('m_state',{
                            rules:[{required:true,message:'请输入钥匙状态！'}]
                        })(
                            <Select style={{width:'100%'}} placeholder="请选择钥匙状态" disabled={this.state.submitFlag == 'show' ? true : false}>
                                <Option value="0">未借出</Option>
                                <Option value="1">已借出</Option>
                            </Select>
                        )}
                    </FormItem>
                </Col>
                <Col span={24}>
                    <FormItem label='附属物品：'>
                        {getFieldDecorator('m_keySpecie',{
                            rules:[{required:true,message:'请选择附属物品！'}]
                        })(<CheckboxGroup options={this.state.keySpecies}  disabled={this.state.submitFlag == 'show' ? true : false}/>
                        )}
                    </FormItem>
                </Col>
            </Row>
            <div style={{display:this.state.submitFlag == 'show'?'block':'none'}}>
            钥匙借款记录：
            <Table
              border={true}
              columns={m_columns}
              size={'small'}
              dataSource={this.state.m_tableData}
              pagination={{
                defaultPageSize: that.state.m_pageSize,
                current: that.state.m_current,
                onChange: that.m_pageChange,
                total: that.state.m_totalSize,
                showTotal: total => `共 ${total} 项`
              }}/>
            </div>
          </Modal>
        </div>
      </PageHeaderWrapper>
    );
  }
}

const WrappedApp = Form.create()(KeyManagement);

export default WrappedApp;
